<?php

namespace App\Api\V1\Controllers;


use App\Extend\WxApp\WXBizDataCrypt;
use App\Models\Media;
use App\Models\WxUser;
use App\User;
use Auth;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Facades\JWTAuth;


class UserController extends BaseController
{

    public function info()
    {

    }


    public function follow_media(Request $request)
    {
        $id = $request->input("id");
        $media = Media::find($id);
        $user = \Auth::user();
        if ($user->isFollowing($media)) {
            return $this->response->array(['status_code' => 0, 'message' => '已关注', 'data' => []]);
        } else {
            $re = $user->follow($media);

            return $this->response->array(['status_code' => 200, 'message' => '关注成功', 'data' => $re]);
        }


    }

    public function app_login(Request $request)
    {
        if (Auth::attempt(['email' => $request->input('email'), 'password' => $request->input('password')])) {
            $user = Auth::getUser();
            $token = JWTAuth::fromUser($user);

            $user['token'] = $token;
            $user['token_exceed'] = time() + config('jwt.ttl') * 60;

            return $this->response->array(['status_code' => 200, 'message' => '登录成功', 'data' => $user]);
        } else {
            return $this->response->array(['status_code' => 0, 'message' => '账号或密码错误']);
        }


    }

    public function register(Request $request)
    {
        $v = $this->validator($request->all());

        if ($v->fails()) {
            return $this->response->array(['status_code' => 0, 'message' => $v->getMessageBag()->first(), 'data' => []]);
        }

        event(new Registered($user = $this->create($request->all())));

        $this->guard()->login($user);

        $token = JWTAuth::fromUser($user);

        $user['token'] = $token;

        return $this->response->array(['status_code' => 200, 'message' => '注册成功', 'data' => $user]);

    }

    public function login(Request $request)
    {

        $code = $request->input("code");
        $encryptedData = $request->input("encryptedData");
        $iv = $request->input("iv");
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . config('wx.xcx_AppID') . "&secret=" . config('wx.xcx_AppSecret') . "&js_code=" . $code . "&grant_type=authorization_code";
        $http = new \GuzzleHttp\Client();
        $res = $http->get($url);
        $re_data = json_decode($res->getBody(), true);
        $pc = new WXBizDataCrypt(config('wx.xcx_AppID'), $re_data['session_key']);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);
        if ($errCode == 0) {
            $data = json_decode($data);
            $wx_user = WxUser::updateOrCreate(['open_id' => $data->openId], [
                'open_id' => $data->openId,
                'nick_name' => $data->nickName,
                'avatar_url' => $data->avatarUrl,
                'city' => $data->city,
                'country' => $data->country,
                'gender' => $data->gender,
                'language' => $data->language,
                'province' => $data->province,
                'app_id' => config('wx.xcx_AppID'),
            ]);
            if ($wx_user->user_id <= 0) {
                $user = User::firstOrCreate(['wx_user_id' => $wx_user->id], [
                    'name' => $data->nickName,
                    'email' => md5($data->openId) . "@ystc168.com",
                    'password' => bcrypt($data->openId),
                    'is_auth' => 0,
                    'wx_user_id' => $wx_user->id,
                    'avatar' => $wx_user->avatar_url,
                ]);
                if ($user->id <= 0) {
                    return $this->response->array(['states_code' => $errCode, 'message' => '用户创建失败']);
                } else {
                    $wx_user->user_id = $user->id;
                    $wx_user->save();
                }
            } else {
                $user = User::findOrFail($wx_user->user_id);
            }

            $token = JWTAuth::fromUser($user);

            $user['token'] = $token;
            $user['ttl'] = config('jwt.ttl');

            return $this->response->array(['states_code' => 200, 'message' => '登录成功', 'data' => $user]);

        } else {
            return $this->response->array(['states_code' => $errCode, 'message' => '登录失败']);
        }


    }
}